import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Search, Mic, MicOff, Send, User, Bot, Star, MessageCircle } from 'lucide-react';
import './App.css';

const API_BASE = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:3000';

function App() {
  const [roles, setRoles] = useState([]);
  const [selectedRole, setSelectedRole] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredRoles, setFilteredRoles] = useState([]);
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isListening, setIsListening] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [conversationId, setConversationId] = useState(null);
  const [showSkills, setShowSkills] = useState(false);

  // 语音识别
  const [recognition, setRecognition] = useState(null);

  useEffect(() => {
    // 初始化语音识别
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
      const recognitionInstance = new SpeechRecognition();
      recognitionInstance.continuous = false;
      recognitionInstance.interimResults = false;
      recognitionInstance.lang = 'zh-CN';

      recognitionInstance.onresult = (event) => {
        const transcript = event.results[0][0].transcript;
        setInputMessage(transcript);
        setIsListening(false);
      };

      recognitionInstance.onerror = () => {
        setIsListening(false);
      };

      recognitionInstance.onend = () => {
        setIsListening(false);
      };

      setRecognition(recognitionInstance);
    }

    // 加载角色列表
    loadRoles();
  }, []);

  useEffect(() => {
    // 搜索过滤
    if (searchQuery.trim()) {
      const filtered = roles.filter(role =>
        role.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        role.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        role.skills.some(skill => skill.toLowerCase().includes(searchQuery.toLowerCase()))
      );
      setFilteredRoles(filtered);
    } else {
      setFilteredRoles(roles);
    }
  }, [searchQuery, roles]);

  const loadRoles = async () => {
    try {
      const response = await axios.get(`${API_BASE}/api/roles`);
      setRoles(response.data);
      setFilteredRoles(response.data);
    } catch (error) {
      console.error('加载角色失败:', error);
    }
  };

  const selectRole = (role) => {
    setSelectedRole(role);
    setMessages([]);
    setConversationId(null);
    setShowSkills(false);
  };

  const startListening = () => {
    if (recognition && !isListening) {
      setIsListening(true);
      recognition.start();
    }
  };

  const stopListening = () => {
    if (recognition && isListening) {
      recognition.stop();
      setIsListening(false);
    }
  };

  const sendMessage = async () => {
    if (!inputMessage.trim() || !selectedRole || isLoading) return;

    const userMessage = { role: 'user', content: inputMessage };
    setMessages(prev => [...prev, userMessage]);
    setInputMessage('');
    setIsLoading(true);

    try {
      const response = await axios.post(`${API_BASE}/api/chat`, {
        roleId: selectedRole.id,
        message: inputMessage,
        conversationId: conversationId
      });

      const aiMessage = { role: 'assistant', content: response.data.response };
      setMessages(prev => [...prev, aiMessage]);
      setConversationId(response.data.conversationId);

      // 语音播放AI回复
      speakText(response.data.response);
    } catch (error) {
      console.error('发送消息失败:', error);
      const errorMessage = { role: 'assistant', content: '抱歉，我现在无法回复。请稍后再试。' };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  const speakText = (text) => {
    if ('speechSynthesis' in window) {
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = 'zh-CN';
      utterance.rate = 0.9;
      utterance.pitch = 1;
      speechSynthesis.speak(utterance);
    }
  };

  const showRoleSkills = async (skillType) => {
    if (!selectedRole) return;

    try {
      const response = await axios.post(`${API_BASE}/api/roles/${selectedRole.id}/skill`, {
        skillType: skillType
      });

      const skillMessage = { role: 'assistant', content: response.data.skillResponse };
      setMessages(prev => [...prev, skillMessage]);
      speakText(response.data.skillResponse);
    } catch (error) {
      console.error('技能展示失败:', error);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  if (!selectedRole) {
    return (
      <div className="app">
        <div className="header">
          <h1>🎭 AI角色扮演聊天</h1>
          <p>选择你感兴趣的角色，开始一段有趣的对话吧！</p>
        </div>

        <div className="search-container">
          <div className="search-box">
            <Search className="search-icon" />
            <input
              type="text"
              placeholder="搜索角色，如：苏格拉底、哈利波特、莎士比亚..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>

        <div className="roles-grid">
          {filteredRoles.map(role => (
            <div key={role.id} className="role-card" onClick={() => selectRole(role)}>
              <div className="role-avatar">
                {role.name.charAt(0)}
              </div>
              <h3>{role.name}</h3>
              <p>{role.description}</p>
              <div className="role-skills">
                {role.skills.map((skill, index) => (
                  <span key={index} className="skill-tag">{skill}</span>
                ))}
              </div>
            </div>
          ))}
        </div>

        {filteredRoles.length === 0 && (
          <div className="no-results">
            <p>没有找到匹配的角色，请尝试其他关键词。</p>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="app">
      <div className="chat-header">
        <button className="back-button" onClick={() => setSelectedRole(null)}>
          ← 返回角色选择
        </button>
        <div className="current-role">
          <div className="role-avatar">{selectedRole.name.charAt(0)}</div>
          <div>
            <h2>{selectedRole.name}</h2>
            <p>{selectedRole.description}</p>
          </div>
        </div>
        <button 
          className="skills-button"
          onClick={() => setShowSkills(!showSkills)}
        >
          <Star className="icon" />
          技能
        </button>
      </div>

      {showSkills && (
        <div className="skills-panel">
          <h3>角色技能</h3>
          <div className="skills-grid">
            <button onClick={() => showRoleSkills('demo')}>
              <MessageCircle className="icon" />
              技能演示
            </button>
            <button onClick={() => showRoleSkills('knowledge')}>
              <Bot className="icon" />
              知识问答
            </button>
            <button onClick={() => showRoleSkills('interaction')}>
              <User className="icon" />
              特殊互动
            </button>
          </div>
        </div>
      )}

      <div className="chat-container">
        <div className="messages">
          {messages.map((message, index) => (
            <div key={index} className={`message ${message.role}`}>
              <div className="message-avatar">
                {message.role === 'user' ? <User /> : <Bot />}
              </div>
              <div className="message-content">
                {message.content}
              </div>
            </div>
          ))}
          {isLoading && (
            <div className="message assistant">
              <div className="message-avatar">
                <Bot />
              </div>
              <div className="message-content loading">
                <div className="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="input-container">
          <div className="input-box">
            <textarea
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入消息或点击麦克风进行语音输入..."
              rows="1"
            />
            <div className="input-actions">
              <button
                className={`voice-button ${isListening ? 'listening' : ''}`}
                onClick={isListening ? stopListening : startListening}
                disabled={!recognition}
              >
                {isListening ? <MicOff /> : <Mic />}
              </button>
              <button
                className="send-button"
                onClick={sendMessage}
                disabled={!inputMessage.trim() || isLoading}
              >
                <Send />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

